package com.grupoconstruobras.sigo.general.interceptores;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
//FIXME: import org.jboss.solder.el.Expressions;

//@WebFilter(filterName = "GeneralFilter", urlPatterns = { "/home.xhtml", "/general/*", "/bienes/*" })
public class SijypFilter implements Filter {

  private static final Logger log = Logger.getLogger("SIJYP");

  public SijypFilter() {

  }

  public void destroy() {

  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getUserPrincipal() != null) {
      if (httpRequest.getHeader("Faces-Request") != null
          && httpRequest.getHeader("Faces-Request").contains("partial/ajax")) {
        PrintWriter pw = response.getWriter();
        pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        pw.println("<partial-response><redirect url=\"" + httpRequest.getContextPath()
                   + "/home.xhtml?reason=sessionExpired\"></redirect></partial-response>");
        pw.flush();
      }
      else {
        /*FIXME: log.warnv("Intento de acceso no autorizado de {0} a {1}", request.getRemoteAddr(),
                  httpRequest.getRequestURL());*/
        httpResponse.sendRedirect(httpRequest.getContextPath()
                                  + "/home.xhtml?reason=notAllowedAccess");

      }
      // }else if (!identidad.hasPermission(new
      // URL(httpRequest.getRequestURL().toString()),ViewPermissions.ACCESS.getValor())){
      // httpResponse.sendRedirect(httpRequest.getContextPath()+"/home.xhtml");
      // log.warnv("Intento de acceso no autorizado de {0} a {1}",identidad.getUser(),httpRequest.getRequestURL());
      // identidad.logout();
      // TODO: Completar con privilegios de autorización
    }
    else {
      // pass the request along the filter chain
      chain.doFilter(request, response);
    }
  }

  public void init(FilterConfig fConfig) throws ServletException {

  }

}
